const express = require('express');
const cors = require('cors');
const { PrismaClient } = require('@prisma/client');

const app = express();
const prisma = new PrismaClient();
const PORT = process.env.PORT || 3001;

// 中间件
app.use(cors());
app.use(express.json());

// 健康检查端点
app.get('/api/health', (req, res) => {
  res.status(200).json({ status: 'healthy', timestamp: new Date().toISOString() });
});

// 用户认证API
app.post('/api/auth/login', async (req, res) => {
  try {
    const { email, password } = req.body;
    
    // 这里应该实现实际的认证逻辑
    const user = await prisma.user.findUnique({
      where: { email }
    });

    if (!user) {
      return res.status(401).json({ error: '用户不存在' });
    }

    // 这里应该验证密码
    res.json({ success: true, user: { id: user.id, email: user.email, role: user.role } });
  } catch (error) {
    res.status(500).json({ error: '服务器错误' });
  }
});

// 实验管理API
app.get('/api/experiments', async (req, res) => {
  try {
    const experiments = await prisma.experiment.findMany({
      include: { createdBy: true }
    });
    res.json({ success: true, experiments, total: experiments.length });
  } catch (error) {
    res.status(500).json({ error: '获取实验列表失败' });
  }
});

app.post('/api/experiments', async (req, res) => {
  try {
    const { title, description, startTime, endTime } = req.body;
    
    if (!title) {
      return res.status(400).json({ error: '标题不能为空' });
    }

    const experiment = await prisma.experiment.create({
      data: {
        title,
        description,
        startTime: startTime ? new Date(startTime) : null,
        endTime: endTime ? new Date(endTime) : null,
        createdById: 1 // 默认管理员创建
      }
    });

    res.json({ success: true, experiment });
  } catch (error) {
    res.status(500).json({ error: '创建实验失败' });
  }
});

app.put('/api/experiments/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { title, description, startTime, endTime } = req.body;

    const experiment = await prisma.experiment.update({
      where: { id: parseInt(id) },
      data: {
        title,
        description,
        startTime: startTime ? new Date(startTime) : null,
        endTime: endTime ? new Date(endTime) : null
      }
    });

    res.json({ success: true, experiment });
  } catch (error) {
    res.status(404).json({ error: '实验不存在' });
  }
});

app.delete('/api/experiments/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    await prisma.experiment.delete({
      where: { id: parseInt(id) }
    });

    res.json({ success: true, message: '实验删除成功' });
  } catch (error) {
    res.status(404).json({ error: '实验不存在' });
  }
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`Backend API server running on port ${PORT}`);
});

// 优雅关闭
process.on('SIGTERM', async () => {
  console.log('SIGTERM received, shutting down gracefully');
  await prisma.$disconnect();
  process.exit(0);
}); 
 